package servers;
import java.io.BufferedReader;
import java.io.InputStreamReader;

import javax.xml.ws.Endpoint;

import user.AuthLevel;
import user.User;
import user.UserDataBase;
import webServices.MetaDraw;

public class DrawProxy {

	public static int nbUsers = 0;
	
	public static void main(String[] args) {
		MetaDraw md = new MetaDraw();
		
		Boolean running = true;
		
		md.addWS("http://localhost:8180/photoshop");
		md.addWS("http://localhost:8280/photoshop");
		
		Endpoint endpointRoot = Endpoint.publish("http://localhost:8080/metaphotoshop", md);

		try {
			System.out.println("-- Welcome on the Image Manager Web Service PROXY Server ! --");
			
			while(running) {
				InputStreamReader isr = new InputStreamReader(System.in); 
				BufferedReader br=new BufferedReader(isr); 
				System.out.print("root@server:");
				String line = br.readLine();
				
				String[] cmd = line.split("\\s");
				
				if(cmd[0].equalsIgnoreCase("addUser") && cmd.length == 3) {
					System.out.println("Adding user nammed '"+cmd[1]+"'");
					
					if(cmd[2].equalsIgnoreCase("normal")) {
						UserDataBase.getInstance().addUser(new User(cmd[1], AuthLevel.SIMPLE_USER));
					}
					else if(cmd[2].equalsIgnoreCase("admin")) {
						UserDataBase.getInstance().addUser(new User(cmd[1], AuthLevel.ADMIN));
					}
					else {
						System.out.println("The priority "+cmd[2]+" doesn't exist");
					}
				}
				
				if(cmd[0].equalsIgnoreCase("quit") && cmd.length == 1) {
					System.out.println("-- Shutdowning the server --");
					System.out.println("-- See ya ! --");
					running = false;
				}
				
				if(cmd[0].equalsIgnoreCase("listUsers") && cmd.length == 1) {
					for(User u : UserDataBase.getInstance().getUsers()) {
						System.out.println(u.getId());
					}
				}
				
				if(cmd[0].equalsIgnoreCase("saveDB") && cmd.length == 1) {
					UserDataBase.getInstance().saveDB();
				}
				
				if(cmd[0].equalsIgnoreCase("loadDB") && cmd.length == 1) {
					UserDataBase.getInstance().loadDB();
				}
				
				if(cmd[0].equalsIgnoreCase("listWS") && cmd.length == 1) {
					System.out.println("--info : running web services :");
					for(Object o : md.getWebServicesList().keySet()) {
						System.out.println("\t"+o.toString()+"\tLoad: "+md.getWebServicesList().get(o)+"/"+md.getLoadLimit());
					}
					System.out.print("root@server:");
				}
				
				if(cmd[0].equalsIgnoreCase("addWS") && cmd.length == 2) {
					try {
						md.addWS(cmd[1]);
					}catch(Exception e) {
						System.out.println("\n--ERROR : Your URL was incorect");
					}
				}
			}
		} catch (Exception e) { }
		endpointRoot.stop();
	}
}